<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:furniture:add']"
        >新增家具</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:furniture:remove']"
        >删除选中</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          @click="toggleSelectAll"
        >全选</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="app-container furniture-container">
      <!-- 搜索栏 -->
      <el-card class="search-card">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="家具名称" prop="furnitureName">
            <el-input
              v-model="queryParams.furnitureName"
              placeholder="请输入名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="家具类型" prop="typeId">
            <el-select v-model="queryParams.typeId" placeholder="请选择类型" clearable>
              <el-option
                v-for="dict in dict.type.furniture_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="家具风格" prop="styleId">
            <el-select v-model="queryParams.styleId" placeholder="请选择风格" clearable>
              <el-option
                v-for="dict in dict.type.furniture_style"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="家具品牌" prop="brandId">
            <el-select v-model="queryParams.brandId" placeholder="请选择品牌" clearable>
              <el-option
                v-for="dict in dict.type.furniture_brand"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="家具材料" prop="material">
            <el-input
              v-model="queryParams.material"
              placeholder="请输入材料"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="规格尺寸" prop="size">
            <el-input
              v-model="queryParams.size"
              placeholder="规格尺寸"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="租赁价格" prop="rentalPrice">
            <el-input-number
              v-model="queryParams.rentalPrice"
              placeholder="租赁价格"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="押金金额" prop="depositRequirement">
            <el-input-number
              v-model="queryParams.depositRequirement"
              placeholder="押金金额"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="是否租赁" prop="isAvailable">
            <el-select v-model="queryParams.isAvailable" placeholder="请选择状态" clearable>
              <el-option label="可出租" value="0"></el-option>
              <el-option label="不可出租" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">发布新家具</el-button>
        <el-button icon="el-icon-download" @click="handleExport">导出数据</el-button>
      </div>

      <!-- 卡片列表 -->
      <el-row :gutter="20" class="furniture-list">
        <el-col
          v-for="item in furnitureList"
          :key="item.furnitureId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          class="furniture-item"
        >
          <el-card class="item-card" shadow="hover">
            <div class="card-header">
              <el-checkbox v-model="item.selected" @change="handleSelectionChange"></el-checkbox>
              <image-preview
                :src="item.imagePaths"
                :width="240"
                :height="160"
                class="furniture-image"
              />
              <div class="price-tag">
                <span class="price">{{ item.rentalPrice }}</span>
                <span class="unit">元/年</span>
              </div>
            </div>

            <div class="card-body">
              <h3 class="title">{{ item.furnitureName }}</h3>
              <div class="meta-info">
                <span class="size">{{ item.size }}</span>
                <el-tag
                  type="info"
                  size="mini"
                  class="status-tag"
                >{{ item.isAvailable === 0 ? '可出租' : '不可出租' }}
                </el-tag><br>
              </div>
            </div>

            <div class="card-footer">
              <el-button
                size="mini"
                @click="handleUpdate(item)"
                class="edit-btn"
              >查看家具</el-button>
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(item)"
              >删除</el-button>
              <!-- 新增出租按钮，仅在家具可出租时显示 -->
              <el-button
                v-if="item.isAvailable === 0"
                type="success"
                size="mini"
                @click="handleRent(item)"
              >出租</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 弹窗部分保持原有逻辑不变 -->
      <!-- ... -->
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[8, 16, 32, 64]"
      @pagination="getList"
    />

    <!-- 添加或修改家具管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="家具名称" prop="furnitureName">
          <el-input v-model="form.furnitureName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="家具类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择类型">
            <el-option
              v-for="dict in dict.type.furniture_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家具风格" prop="styleId">
          <el-select v-model="form.styleId" placeholder="请选择风格">
            <el-option
              v-for="dict in dict.type.furniture_style"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家具品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择品牌">
            <el-option
              v-for="dict in dict.type.furniture_brand"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家具材料" prop="material">
          <el-input v-model="form.material" placeholder="请输入材料" />
        </el-form-item>
        <el-form-item label="家具的颜色" prop="colorId">
          <el-checkbox-group v-model="form.colorId">
            <el-checkbox
              v-for="dict in dict.type.furniture_color"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="家具的规格尺寸" prop="size">
          <el-input v-model="form.size" placeholder="请输入规格尺寸" />
        </el-form-item>
        <el-form-item label="家具图片" prop="imagePaths">
          <image-upload v-model="form.imagePaths"/>
        </el-form-item>
        <el-form-item label="家具的租赁价格" prop="rentalPrice">
          <el-input v-model="form.rentalPrice" placeholder="请输入租赁价格" />
        </el-form-item>
        <el-form-item label="家具所需的押金金额" prop="depositRequirement">
          <el-input v-model="form.depositRequirement" placeholder="请输入押金金额" />
        </el-form-item>
        <el-form-item label="配送家具的费用" prop="deliveryFeeRule">
          <el-input v-model="form.deliveryFeeRule" placeholder="请输入配送费用" />
        </el-form-item>
        <el-form-item label="家具库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="是否租赁" prop="isAvailable">
          <el-radio-group v-model="form.isAvailable">
            <el-radio label="0">可出租</el-radio>
            <el-radio label="1">不可出租</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="家具详细信息">
          <editor v-model="form.detailedDescription" :min-height="192"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="rentTitle" :visible.sync="rentOpen" width="500px" append-to-body>
      <el-form ref="rentForm" :model="rentForm" label-width="120px">
        <el-form-item label="家具ID" prop="furnitureId">
          <el-input v-model="rentForm.furnitureId" disabled />
        </el-form-item>
        <el-form-item label="租几个" prop="rentQuantity">
          <el-input-number v-model="rentForm.rentQuantity" :min="1" :max="form.stock" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="租赁开始时间" prop="rentalStartDate">
          <el-date-picker v-model="rentForm.rentalStartDate" type="date" placeholder="选择开始时间" />
        </el-form-item>
        <el-form-item label="租赁结束时间" prop="rentalEndDate">
          <el-date-picker v-model="rentForm.rentalEndDate" type="date" placeholder="选择结束时间" />
        </el-form-item>
        <el-form-item label="押金金额" prop="depositRequirement">
          <el-input-number v-model="rentForm.depositRequirement" placeholder="请输入押金金额" />
        </el-form-item>
        <el-form-item label="租赁价格" prop="rentalPrice">
          <el-input-number v-model="rentForm.rentalPrice" placeholder="请输入租赁价格" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input-number v-model="rentForm.totalAmount" disabled />
        </el-form-item>
        <el-form-item label="配送地址" prop="deliveryAddress">
          <el-input v-model="rentForm.deliveryAddress" placeholder="请输入配送地址" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="rentForm.paymentMethod" placeholder="请选择支付方式">
            <el-option label="微信" value="微信"></el-option>
            <el-option label="支付宝" value="支付宝"></el-option>
            <el-option label="银行卡" value="银行卡"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户备注" prop="userRemark">
          <el-input v-model="rentForm.userRemark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRentForm">确 定</el-button>
        <el-button @click="cancelRent">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFurniture, getFurniture, delFurniture, addFurniture, updateFurniture, rentFurniture } from "@/api/system/furniture";

export default {
  name: "Furniture",
  dicts: ['furniture_brand', 'furniture_style', 'furniture_type', 'furniture_color'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家具管理表格数据
      furnitureList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 8,
        furnitureName: null,
        typeId: null,
        styleId: null,
        brandId: null,
        material: null,
        colorId: null,
        size: null,
        rentalPrice: null,
        depositRequirement: null,
        deliveryFeeRule: null,
        isAvailable: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        furnitureName: [
          { required: true, message: "家具名称不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "家具类型不能为空", trigger: "change" }
        ],
        rentalPrice: [
          { required: true, message: "家具的租赁价格不能为空", trigger: "blur" }
        ],
        depositRequirement: [
          { required: true, message: "家具所需的押金金额不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "家具库存数量不能为空", trigger: "blur" }
        ],
        isAvailable: [
          { required: true, message: "是否租赁不能为空", trigger: "blur" }
        ],
      },

      // 添加全选状态
      selectAll: false,
      rentOpen: false,
      rentTitle: "",
      rentForm: {
        furnitureId: null,
        rentQuantity: 1,
        rentalStartDate: '',
        rentalEndDate: '',
        depositRequirement: 0,
        rentalPrice: 0,
        totalAmount: 0,
        deliveryAddress: '',
        paymentMethod: '',
        userRemark: ''
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询家具管理列表 */
    getList() {
      this.loading = true;
      listFurniture(this.queryParams).then(response => {
        this.furnitureList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        furnitureId: null,
        furnitureName: null,
        typeId: null,
        styleId: null,
        brandId: null,
        material: null,
        colorId: [],
        size: null,
        imagePaths: null,
        rentalPrice: null,
        depositRequirement: null,
        deliveryFeeRule: null,
        stock: null,
        isAvailable: null,
        detailedDescription: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.ids = this.furnitureList.filter(item => item.selected).map(item => item.furnitureId);
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
      this.selectAll = this.furnitureList.every(item => item.selected);
    },

    // 添加全选功能
    toggleSelectAll() {
      this.selectAll = !this.selectAll;
      this.furnitureList.forEach(item => {
        item.selected = this.selectAll;
      });
      this.handleSelectionChange();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加家具管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const furnitureId = row.furnitureId || this.ids
      getFurniture(furnitureId).then(response => {
        this.form = response.data;
        this.form.colorId = this.form.colorId.split(",");
        this.form.isAvailable = this.form.isAvailable.toString(); // 确保 isAvailable 是字符串类型
        this.open = true;
        this.title = "修改家具管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
        this.$refs["form"].validate(valid => {
            if (valid) {
                // 检查库存是否为0，如果是，则将isAvailable设置为1（不可出租）
                if (this.form.stock === 0) {
                    this.form.isAvailable = '1';
                }
                this.form.colorId = this.form.colorId.join(",");
                if (this.form.furnitureId != null) {
                    updateFurniture(this.form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.getList();
                    });
                } else {
                    addFurniture(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
            }
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const furnitureIds = row ? row.furnitureId : this.ids.join(',');
      this.$modal.confirm('是否确认删除家具管理编号为"' + furnitureIds + '"的数据项？').then(function () {
        return delFurniture(furnitureIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/furniture/export', {
        ...this.queryParams
      }, `furniture_${new Date().getTime()}.xlsx`)
    },
    handleRent(row) {
      this.rentForm.furnitureId = row.furnitureId;
      this.rentForm.rentQuantity = 1;
      this.rentForm.rentalStartDate = '';
      this.rentForm.rentalEndDate = '';
      this.rentForm.depositRequirement = row.depositRequirement;
      this.rentForm.rentalPrice = row.rentalPrice;
      this.rentForm.totalAmount = this.rentForm.depositRequirement + this.rentForm.rentalPrice;
      this.rentForm.deliveryAddress = '';
      this.rentForm.paymentMethod = '';
      this.rentForm.userRemark = '';
      this.rentOpen = true;
      this.rentTitle = "出租家具";
    },
    cancelRent() {
      this.rentOpen = false;
      this.resetRentForm();
    },
    resetRentForm() {
      this.rentForm = {
        furnitureId: null,
        rentQuantity: 1,
      };
      this.resetForm("rentForm");
    },
    submitRentForm() {
      this.$refs["rentForm"].validate(valid => {
        if (valid) {
          // 计算总金额并格式化为小数点后两位
          this.rentForm.totalAmount = (this.rentForm.depositRequirement + this.rentForm.rentalPrice * this.rentForm.rentQuantity).toFixed(2);
          rentFurniture(this.rentForm).then(response => {
            this.$modal.msgSuccess("出租成功");
            this.rentOpen = false;
            this.resetRentForm();
            this.getList();
          });
        }
      });
    },
  }
};
</script>

<style scoped>
.furniture-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  background: #f5f7fa;
}

.search-input {
  width: 240px;
}

.price-input {
  width: 120px;
}

.price-separator {
  margin: 0 10px;
  color: #909399;
}

.operation-bar {
  margin-bottom: 20px;
}

.furniture-list {
  margin-bottom: 30px;
}

.item-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.item-card:hover {
  transform: translateY(-5px);
}

.card-header {
  position: relative;
}

.price-tag {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 4px 12px;
  border-radius: 4px;
}

.price {
  font-size: 18px;
  font-weight: bold;
}

.unit {
  font-size: 12px;
  margin-left: 2px;
}

.card-body {
  padding: 15px;
}

.title {
  margin: 0 0 12px;
  font-size: 16px;
  color: #303133;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.address {
  color: #606266;
  font-size: 12px;
}

.card-footer {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
  text-align: right;
}

.custom-pagination {
  margin-top: 30px;
}
</style>
